package com.googlecode.allinclusive.fw.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * GZip Filter for Soap 
  */
public class GZipFilter implements Filter {

	public void init(FilterConfig fConfig) throws ServletException {
	}

	/**
	 * GZIP压缩处理
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		if (isGZipEncoding(req)) {
			// GZIP压缩
			GZipHttpResponse gzipResp = new GZipHttpResponse(res);
			res.setHeader("Content-Encoding", "gzip");
			chain.doFilter(request, gzipResp);
			gzipResp.flush();
		} else {
			chain.doFilter(request, response);
		}
	}
	
	public void destroy() {
	}

	/** 
	 * 判断浏览器是否支持GZIP 
	 * @param request HTTP请求 
	 * @return true/false
	 */
	private static boolean isGZipEncoding(HttpServletRequest request) {
		boolean supportGzip = false;
		String encoding = request.getHeader("Content-Encoding");
		if (encoding != null && encoding.toLowerCase().indexOf("gzip") != -1) {
			supportGzip = true;
		}
		return supportGzip;
	}
}
